# -*- codeing = utf-8 -*-
# @Time : 2022/2/18 13:13
# @File : catch_face.py
# @Software : PyCharm
import time
import cv2
import os

from config import DATA_TRAIN
from utils import makedir_exist_ok

                # 抓举人脸标记，根据tag保存目录，窗口名字，设备索引）
def catch_video(tag, window_name='catch face', camera_idx=0):
    cv2.namedWindow(window_name)
    # 调用摄像头
    cap = cv2.VideoCapture(camera_idx)
    count = 0
    while cap.isOpened():
        # 读一帧
        ok, frame = cap.read()
        if not ok:
            break
        # 抓取人脸
        catch_face(frame, tag)
        count += 1
        if count == 600:
            break
        cv2.imshow(window_name, frame)
        # 退出程序
        c = cv2.waitKey(1)
        if c & 0xFF == ord('q'):
            break
    # 设防摄像头，关闭窗口
    cap.release()
    cv2.destroyAllWindows()

# 人脸抓取
def catch_face(frame, tag):
    # opencv的人脸分类器
    classfier = cv2.CascadeClassifier("D:\\Anaconda\\Lib\site-packages\\cv2\\data\haarcascade_frontalface_alt2.xml")
    color = (0, 255, 0)
    # 当前帧转成灰度图
    grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 人脸检测，1.2和2为图片缩放比例和需要检测的有效点数
    face_rects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
    # 图像数据rbg转一维灰度
    # 图像缩放比例
    # 对特折监测点周边多少有效点同时检测
    # 特征检测点的最小值
    num = 1
    if len(face_rects) > 0: #大于0则检测到人脸
        for face_rects in face_rects:
            # 图片帧中有多个脸，框出每一个脸
            x, y, w, h = face_rects
            image = frame[y - 10:y + h + 10, x - 10:x + w + 10]
            # 保存人脸
            flag = save_face(image, tag, num)
            cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
            num += 1



def save_face(image, tag, num):
    # 判断人脸是否存在，不在就创建目录
    makedir_exist_ok(os.path.join(DATA_TRAIN, str(tag)))
    img_name = os.path.join(DATA_TRAIN, str(tag), '{}_{}.jpg'.format(int(time.time()), num))
    # 保存人脸图像，用于训练
    cv2.imwrite(img_name, image)

